package com.googlecode.cswish.security.auth;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * TODO: I'll optimize it in future
 * 
 * @author Jerry.Feng Date: 2004-12-30 10:41:05
 * @version $id: $
 */
public class FastCache {
    public static final int INIT_CAPACITY = 100;
    private HashMap map;    
    
    public FastCache() {
    	map = new HashMap(INIT_CAPACITY);
    }
    
    public FastCache(int initialCapacity) {
    	map = new HashMap(initialCapacity);
    }
    
    public void addElement(Object arg0, Object arg1) {
        map.put(arg0,arg1);
    }
    
    public Object getElement(Object arg0) {
        return map.get(arg0);
    }
    
    public int size() {
        return map.size();
    }
    
    public int capacity() {
        int capcity = map.size();
        if (capcity >= INIT_CAPACITY) {
            return 0;
        } else {
            return INIT_CAPACITY - capcity;
        }
    }
    
    public Map toMap() {    	
    	return map;
    }
    
    public void addAll(FastCache fastCache) {
    	map.putAll(fastCache.toMap());
    }
    
    public FastCache intersection(FastCache fastCache) {
    	FastCache ret = new FastCache(map.size() * 4 / 3);   	
    	Iterator its = listKeys();
    	while (its.hasNext()) {
			Object key = (Object) its.next();
			Object value = map.get(key);			
			if (value != null) {
				Object otherValue = fastCache.getElement(key);
				if (value.equals(otherValue)) {
					ret.addElement(key, value);
				}
			}
		}
    	
    	return ret;
    }
    
    public Collection listValues() {
    	return map.values();    	
    }
    
    public Iterator listKeys() {    	
    	return map.keySet().iterator();
    }
}
